<?php


namespace apps\marriage\app\op\controller;


use apps\marriage\core\service\CourseOrderService;
use apps\marriage\core\service\CourseService;
use apps\marriage\core\service\UserService;
use think\Exception;
use think\Request;

class CourseOrderController extends BaseMarriageOpController
{
    /**
     * @var CourseOrderService
     */
    private $courseOrderService;

    /**
     * @var CourseService
     */
    private $courseService;

    /**
     * @var UserService
     */
    private $userService;

    protected function init()
    {
        parent::init();
        $this->courseOrderService = service('CourseOrder', SERVICE_NAMESPACE);
        $this->courseService = service('Course', SERVICE_NAMESPACE);
        $this->userService = service('User', SERVICE_NAMESPACE);
    }

    public function lists(Request $request)
    {
        $pageSize = $request->param('page_size', 10);
        $orderSn = $request->param('sn', '');
        $courseId = $request->param('course_id', 0, 'intval');
        $params = [];
        if(!empty($orderSn)) {
            $params['sn'] = $orderSn;
        }
        if($courseId > 0) {
            $params['course_id'] = $courseId;
        }
        $res = $this->courseOrderService->pageListByParams($params, $pageSize);
        if ($res['data']) {
            $dataList = [];
            foreach ($res['data'] as $rs) {
                $course = $this->courseService->getByPk($rs['course_id']);
                $course = $this->courseService->format($course);
                $dataList[] = [
                    'course' => $course,
                    'order' => $this->courseOrderService->format($rs),
                    'user' => $this->userService->getByPk($rs['user_id'])
                ];
            }
            $res['data'] = $dataList;
        }
        return $this->success($res);
    }

    public function detail(Request $request)
    {
        $sn = $request->param('sn');
        $order = $this->courseOrderService->getBySn($sn);
        if(empty($order)) {
            throw new Exception('订单不存在');
        }
        $order = $this->courseOrderService->format($order);
        $course = $this->courseService->getByPk($order['course_id']);
        $course = $this->courseService->format($course);
        $user = $this->userService->getByPk($order['user_id']);
        return $this->success([
            'course' => $course,
            'order' => $order,
            'user' => $user
        ]);
    }

    public function cancel(Request $request)
    {
        $sn = $request->param('sn');
        $this->courseOrderService->onCancel($sn);
        return $this->success();
    }

    public function modify_money(Request $request)
    {
        $orderSn = $request->param('sn', '');
        $orderMoney = $request->param('pay_money', 0.00, 'floatval');
        $this->courseOrderService->onModifyOrderMoney($orderSn, $orderMoney);
        return $this->success();
    }
}